from exception_handler import GlobalExceptionHandler


class OrderService(GlobalExceptionHandler):
    """订单服务类，继承全局异常处理器"""

    def __init__(self):
        super().__init__()
        # 订单服务的初始化逻辑
        self.orders = {}

    def _extend_exception_data(self, data: dict, e: Exception) -> None:
        """扩展异常数据，添加订单服务特有的信息"""
        data["service"] = "order_service"
        data["version"] = "1.0.0"

    def _post_exception_handler(self, data: dict, e: Exception) -> None:
        """异常处理后的自定义逻辑"""
        if data["severity"] == "critical":
            # 对于严重错误，可以发送报警
            self._send_alert(data)

    def _send_alert(self, data: dict) -> None:
        """发送报警通知"""
        # 实际应用中可以发送邮件、短信或调用报警API
        print(f"ALERT: Critical error in OrderService - {data['message']}")

    def create_order(self, order_id: str, items: list) -> bool:
        """创建订单"""
        # 使用安全执行方法
        return self.execute_safely(self._create_order_impl, order_id, items)

    def _create_order_impl(self, order_id: str, items: list) -> bool:
        """创建订单的实际实现"""
        if not order_id or not items:
            raise ValueError("订单ID和商品列表不能为空")

        if order_id in self.orders:
            raise KeyError(f"订单ID {order_id} 已存在")

        # 模拟一些业务逻辑
        if len(items) > 100:
            # 模拟一个严重错误
            raise MemoryError("订单商品数量过多，内存不足")

        self.orders[order_id] = {
            "items": items,
            "status": "created",
            "timestamp": datetime.utcnow().isoformat(),
        }
        return True


# 使用示例
if __name__ == "__main__":
    # 初始化订单服务
    order_service = OrderService()

    # 正常创建订单
    order_service.create_order("ORD-001", ["item1", "item2"])

    # 触发异常
    order_service.create_order("", [])  # 空订单ID，会触发ValueError

    # 触发已存在的订单ID异常
    order_service.create_order("ORD-001", ["item3"])  # 会触发KeyError

    # 触发严重错误
    large_items = [f"item{i}" for i in range(200)]  # 200个商品，会触发MemoryError
    order_service.create_order("ORD-002", large_items)
